<template>
  <div class="container">
    <el-row>
      <el-col :span="1" style="text-align:center;    display:table;">
        <p class="md-text1">标dfs题:</p>
      </el-col>
      <el-col :span="3">
        <el-input placeholder="标题" v-model="title"></el-input>
      </el-col>
      <el-col :span="1" style="text-align:center;    display:table;">
        <p class="md-text1">分类:</p>
      </el-col>
      <el-col :span="3">
        <el-select  v-model="docType" placeholder="请选择" :value-key="docKey" >
          <el-option
                  v-for="item in this.doc_types"
                  :key="item.Id"
                  :label="item.TypeName"
                  :value="item.Id"
          >
          </el-option>
        </el-select>
      </el-col>
      <el-col :span="1" style="text-align:center;  display:table; margin-top: 10px; font-size: 15px;">
        <el-checkbox v-model="is_public">不公开</el-checkbox>
      </el-col>
    </el-row>
    <el-row style="margin-top:30px;">
      <mavon-editor style="height: 600px" v-model="content" ref="md"  @imgAdd="$imgAdd" />
    </el-row>
    <el-row>
      <el-col :span="24" style="margin-top: 20px">
        <el-button @click="addArticle">{{btnSave}}</el-button>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import Message from "element-ui/lib/message";
import axios from "@/api/ajax.js";
import Cookie from "js-cookie";
import Const from "@/const.js";
export default {
  name: "editor",
  components: {
  },
  data: () => {
    return {
      userInfo: {},
      content: "",
      title: "",
      btnSave:"提交",
      anchorAttrs: {
        target: "_blank",
        rel: "noopener noreferrer nofollow"
      },
      docKey: 0,
      docType:1,
      doc_types:[{Id:"1",TypeName:"fdsafd"}],
      is_public:false,
    };
  },
  methods: {
    // 绑定@imgAdd event
    $imgAdd(pos, $file){
      // 第一步.将图片上传到服务器.
      var formdata = new FormData();
      console.log($file);
      formdata.append('image', $file);
      axios({
        url: process.env.NODE_ENV === 'development'?'http://127.0.0.1:4596/api/image_upload':'https://www.testingcloud.club/sapi/api/image_upload',
        method: 'post',
        data: formdata,
        headers: { 'Content-Type': 'multipart/form-data'},
      }).then((url) => {
        console.log(url);
        var url1 = process.env.NODE_ENV === 'development'?'http://127.0.0.1:4596/api/image_download/':'https://www.testingcloud.club/sapi/api/image_download/' + url.data.url;
        // 第二步.将返回的url替换到文本原位置![...](0) -> ![...](url)
        /**
         * $vm 指为mavonEditor实例，可以通过如下两种方式获取
         * 1. 通过引入对象获取: `import {mavonEditor} from ...` 等方式引入后，`$vm`为`mavonEditor`
         * 2. 通过$refs获取: html声明ref : `<mavon-editor ref=md ></mavon-editor>，`$vm`为 `this.$refs.md`
         */
        this.$refs.md.$img2Url(pos, url1);
      })
    },
    changeType(){

    },
   addArticle() {
     var x
     if(this.btnSave == '提交'){
          for (x in this.doc_types){
            if(this.doc_types[x].Id === this.type){
              this.docType = x;
            }
            //console.log(this.doc_types[x]);
            //console.log(typeof (this.doc_types));
          }
            axios.put("/article", {
                title: this.title,
                content: this.content,
                author: this.userInfo.DisplayName,
                type: Number(this.docType),
                author: this.userInfo.DisplayName,
                is_public: this.is_public?1:0,
            })
                .then(response => {
                    if (response.data.Status === 0) {
                      Message.success("新增文章成功");
                    }
                })
                .catch(reason => {
                  Message.error("网络错误:" + reason);
                });
        }else{
            axios.post("/article_update", {
                title: this.title,
                content: this.content,
                author: this.userInfo.DisplayName,
                type:  this.docType,
                id: new Number(this.$route.query['id']),
              is_public: this.is_public?1:0,
            }).then(response => {
                    if (response.data.Status === 0) {
                      Message.success("更新文章成功");
                    }
                }).catch(reason => {
                  Message.error("网络错误:" + reason);
                });
        }
    }
  },
  created() {
    if (this.$route.query['id'] != undefined ) {
        console.log("query para is ",this.$route.query['id']);
        // 如果有query说明是旧的文档编辑
        //todo 通过接口获取旧的文档，添加到新的文档里面去。
        let url = '/article/' + this.$route.query['id'];
        axios.get(url,{withCredentials:true}).then(
            resp => {
                console.log(resp.data.Data.type);
                this.docType = resp.data.Data.type;
                this.title = resp.data.Data.title;
                this.author = resp.data.Data.author;
                this.content =  resp.data.Data.content;
                this.btnSave = '更新';
                if(resp.data.Data.is_public == 1){
                  this.is_public = true;
                }else{
                  this.is_public = false;
                }
            }
        ).catch(
            reason => {
                Message.error(reason)
            }
        )
    }
    this.userInfo = JSON.parse(Cookie.get(Const.KEY_USER_INFO));

  },
  beforeCreate() {
    axios.get("doc_types",{withCredentials:true}).then(
            resp => {
              this.doc_types = resp.data.Data;
              console.log(this.doc_types);
            }
    ).catch(
            reason => {
              Message.error(reason)
            }
    )
  }
};
</script>
<style >
.container {
  width: 100%;
}
.md-text {
  font-size: 12px;
  width: 100%;
}
.md-body {
  width: 100%;
  margin-left: 20px;
}
.md-text1 {
  font-size: 15px;
  margin-top: 10px;
}
.mavonEditor {
  width: 100%;
  height: 800px;
}
</style>
